package com.budayi.config;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author LIBOFEI
 * @ClassName MyFallbackProvider
 * @description  在zuul中实现熔断功能需要实现ZuulFallbackProvider的接口
 *               getRoute()的方法 用于指定熔断功能应用于哪些路由的服务
 *               fallbackReponse()的方法为进入熔断功能时执行的逻辑
 * @date 2020/9/12 15:24
 * @Version 1.0
 **/
@Component
public class MyFallbackProvider implements ZuulFallbackProvider {

    @Override
    public String getRoute() {
        return "eureka-client"; //只针对client服务进行熔断
//        return "*";//针对所有服务进行熔断
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("error,i am fallback".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.setContentType(MediaType.APPLICATION_JSON);
                return httpHeaders;
            }
        };
    }
}
